package cn.zyq.demo.service.sys.impl;


import cn.zyq.demo.beans.sys.*;
import cn.zyq.demo.mapper.sys.*;
import cn.zyq.demo.service.sys.SysAdminService;
import cn.zyq.demo.service.sys.SysConfigService;
import cn.zyq.demo.system.common.BaseService;
import cn.zyq.demo.system.common.PageParam;
import cn.zyq.demo.system.ry.UserConstants;
import cn.zyq.demo.system.ry.util.BeanValidators;
import cn.zyq.demo.system.ry.util.SecurityUtils;
import cn.zyq.demo.system.ry.util.SpringUtils;
import cn.zyq.demo.system.ry.util.StringUtils;
import com.aliyun.oss.ServiceException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.Validator;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息表
 * 2023-05-12 20:14:08
 */

@Slf4j
@Service
public class SysAdminServiceImpl extends BaseService implements SysAdminService {
    @Autowired
    private SysAdminMapper sysAdminMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysAdminRoleMapper userRoleMapper;

    @Autowired
    private SysAdminPostMapper userPostMapper;

    @Autowired
    private SysConfigService configService;

    @Autowired
    protected Validator validator;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Override
    public PageInfo<SysAdmin> list(PageParam pageParam, SysAdmin admin) {
        PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
        pageParam.getKv().put("deleted", 0);
        List<SysAdmin> dbList = this.sysAdminMapper.list(pageParam.getKv());
        return new PageInfo<>(dbList);
    }

    @Override
    public int add(SysAdmin param, SysAdmin admin) {
        this.setCreateBaseData(param, admin);
        int i = this.sysAdminMapper.insertSelective(param);
        // 新增用户岗位关联
        insertUserPost(param);
        // 新增用户与角色管理
        insertUserRole(param);
        return i;
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysAdmin user) {
        this.insertUserRole(user.getSysAdminID(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysAdmin user) {
        Integer[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysAdminPost> list = new ArrayList<>(posts.length);
            for (Integer postId : posts) {
                SysAdminPost up = new SysAdminPost();
                up.setSysAdminID(user.getSysAdminID());
                up.setSysPostID(postId);
                list.add(up);
            }
            userPostMapper.insertList(list);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Integer userId, Integer[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysAdminRole> list = new ArrayList<>(roleIds.length);
            for (Integer roleId : roleIds) {
                SysAdminRole ur = new SysAdminRole();
                ur.setSysAdminID(userId);
                ur.setSysRoleID(roleId);
                list.add(ur);
            }
            userRoleMapper.insertList(list);
        }
    }

    @Override
    public int update(SysAdmin param, SysAdmin admin) {
        Integer id = param.getSysAdminID();
        this.setUpdateBaseData(param, admin);

        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(id);
        // 新增用户与角色管理
        insertUserRole(param);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(id);
        // 新增用户与岗位管理
        insertUserPost(param);
        return this.sysAdminMapper.updateByPrimaryKeySelective(param);
    }

    @Override
    public void del(String serviceID, SysAdmin admin) {
        SysAdmin dbInfo = this.detail(serviceID);
        Integer id = dbInfo.getSysAdminID();
        this.deleteLogic(id, admin, this.sysAdminMapper);
    }

    @Override
    public SysAdmin detail(String serviceID, SysAdmin admin) {
        return this.detail(serviceID);
    }

    @Override
    public SysAdmin detail(String serviceID) {
        SysAdmin dbInfo = this.getByServiceID(serviceID, SysAdmin.class, this.sysAdminMapper);
        this.checkLogicExist(dbInfo);
        return dbInfo;
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysAdmin selectUserByUserName(String userName) {
        return sysAdminMapper.selectUserByUserName(userName);
    }

    @Override
    public boolean checkUserNameUnique(SysAdmin sysAdmin) {
        Integer userId = StringUtils.isNull(sysAdmin.getSysAdminID()) ? -1 : sysAdmin.getSysAdminID();
        SysAdmin info = sysAdminMapper.checkUserNameUnique(sysAdmin.getUserName());
        if (StringUtils.isNotNull(info) && !info.getSysAdminID().equals(userId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public boolean registerUser(SysAdmin sysAdmin) {
        this.setCreateBaseData(sysAdmin, SecurityUtils.getLoginUser().getSysAdmin());
        int i = this.sysAdminMapper.insertSelective(sysAdmin);
        return i > 0;
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    @Override
    public boolean checkPhoneUnique(SysAdmin user) {
        Integer userId = StringUtils.isNull(user.getSysAdminID()) ? -1 : user.getSysAdminID();
        SysAdmin info = sysAdminMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && !info.getSysAdminID().equals(userId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public boolean checkEmailUnique(SysAdmin user) {
        Integer userId = StringUtils.isNull(user.getSysAdminID()) ? -1 : user.getSysAdminID();
        SysAdmin info = sysAdminMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && !info.getSysAdminID().equals(userId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public void checkUserAllowed(SysAdmin user) {
        if (StringUtils.isNotNull(user.getSysAdminID()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    @Override
    public void checkUserDataScope(Integer userId) {
        if (!SysAdmin.isAdmin(SecurityUtils.getSysAdminID())) {
            SysAdmin user = new SysAdmin();
            user.setSysAdminID(userId);
            List<SysAdmin> users = SpringUtils.getAopProxy(this).sysAdminMapper.selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    @Override
    public int updateUserProfile(SysAdmin user) {
        return sysAdminMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return sysAdminMapper.updateUserAvatar(userName, avatar) > 0;
    }

    @Override
    public int resetPwd(SysAdmin user) {
        return sysAdminMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public int resetUserPwd(String userName, String password) {
        return sysAdminMapper.resetUserPwd(userName, password);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param param 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysAdmin> selectAllocatedList(PageParam param) {
        return sysAdminMapper.selectAllocatedList(param.getKv());
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param param 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysAdmin> selectUnallocatedList(PageParam param) {
        return sysAdminMapper.selectUnallocatedList(param.getKv());
    }


    /**
     * 根据条件分页查询用户列表
     *
     * @param param 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysAdmin> selectUserList(PageParam param) {
        return sysAdminMapper.list(param.getKv());
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysAdmin> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysAdmin user : userList) {
            try {
                // 验证是否存在这个用户
                SysAdmin u = sysAdminMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    this.add(user, SecurityUtils.getLoginUser().getSysAdmin());
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getSysAdminID());
                    user.setSysAdminID(u.getSysAdminID());

                    this.update(user, SecurityUtils.getLoginUser().getSysAdmin());
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysAdmin selectUserById(Integer userId) {
        SysAdmin sysAdmin = sysAdminMapper.selectByPrimaryKey(userId);
        sysAdmin.setRoles(this.roleMapper.selectRolePermissionByUserId(sysAdmin.getSysAdminID()));
        sysAdmin.setDept(this.sysDeptMapper.selectDeptById(sysAdmin.getSysDeptID()));
        return sysAdmin;
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Integer[] userIds) {
        for (Integer userId : userIds) {
            checkUserAllowed(new SysAdmin(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return sysAdminMapper.deleteUserByIds(userIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysAdmin user) {
        return this.update(user, SecurityUtils.getLoginUser().getSysAdmin());
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Integer userId, Integer[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }
}
